package com.web.struts2;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetails;

import com.opensymphony.xwork2.ActionSupport;
import com.security.domain.User;
import com.security.service.UserService;

/**
 * Struts2 Action基类.
 * 
 * 实现绕过jsp/freemaker,直接输出文本.
 * 
 * @author san
 */

@SuppressWarnings( { "serial" })
public class BaseSupportAction extends ActionSupport {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	public UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getLoginUser() throws Exception {
		try {
			User user = (User) getSession().getAttribute("LoginUser");
			if (user == null) {
				SecurityContext ctx = SecurityContextHolder.getContext();
				Authentication auth = ctx.getAuthentication();
				if (auth.getPrincipal() instanceof UserDetails) {
					org.springframework.security.userdetails.User userd = (org.springframework.security.userdetails.User) auth
							.getPrincipal();
					if (userd != null && userd.getUsername() != null) {
						user = userService.getUserByLoginName(userd
								.getUsername());
						getSession().setAttribute("LoginUser", user);
					}
				}
			}
			return user;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * Convenience method to get the request
	 * 
	 * @return current request
	 */
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * Convenience method to get the response
	 * 
	 * @return current response
	 */
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * Convenience method to get the session. This will create a session if one
	 * doesn't exist.
	 * 
	 * @return the session from the request (request.getSession()).
	 */
	public HttpSession getSession() {
		return getRequest().getSession();
	}

	/**
	 * 绕过Template,直接输出内容的简便函数.
	 */
	protected String render(String text, String contentType) {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType(contentType);
			response.getWriter().write(text);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 直接输出字符串.
	 */
	protected String renderText(String text) {
		return render(text, "text/plain;charset=UTF-8");
	}

	/**
	 * 直接输出HTML.
	 */
	protected String renderHtml(String html) {
		return render(html, "text/html;charset=UTF-8");
	}

	/**
	 * 直接输出XML.
	 */
	protected String renderXML(String xml) {
		return render(xml, "text/xml;charset=UTF-8");
	}

	/*
	 * 得到ActionMapping中的参数,如果参数为空，就默认返回id的值
	 */
	protected String getParams(Object... key) throws Exception {
		ActionMapping mapping = ServletActionContext.getActionMapping();
		Map map = mapping.getParams();
		if (null != map) {
			if (key.length == 0) {
				if (map.containsKey("id")) {
					return map.get("id").toString();
				}
				return "";
			} else {
				return map.get(key[0].toString()).toString();
			}
		}
		return "";
	}
}
